import json
import os

from flask import render_template, request
from flask_login import login_required, current_user
from sqlalchemy import desc

from common.utils.identify import classify
from common.utils.rights import permission_required, view_logging_required
from common.utils.watermelon.extract import watermelon_main
from models import LogModel, RoleModel, MelonModel
from . import index_bp


# 用户增加
@index_bp.get('/melon/info')
@view_logging_required
@permission_required("melon::info")
def melon_main():
    return render_template('admin/melon/melons.html')


@index_bp.get('/melons/add')
@view_logging_required
# @permission_required("melon:add")
def melon_add_view():
    roles = RoleModel.query.all()
    return render_template('admin/melon/melons_add.html', roles=roles)


@index_bp.get('/melons/<id>')
@view_logging_required
# @permission_required("admin:user:edit")
def melon_user_id_view(id):
    melon = MelonModel.query.filter_by(id=id).first()
    return render_template('admin/melon/melons_edit.html', melon=melon)


basedir = os.path.abspath(os.path.dirname(__file__))


@index_bp.post('/melons/upload')
def upload():
    img = request.files.get('melon')
    # path = basedir + "/static/upload/"
    # file_path = path + img.filename
    # img.save('../../static/upload/'+img.filename)
    print(img.filename)
    # 根据图片识别是什么类别
    name = classify(img)
    # temp为返回给前端的结果集
    temp = {}
    # 如果识别结果是西瓜，则进行甜度识别（看是不是好瓜）
    if name == "西瓜":
        isGood = watermelon_main(img)
        # 往结果集添加甜度的字段
        sweet = {"sweet": isGood}
        temp.update(sweet)
    # 根据识别出的类别去数据库查找更详细内容
    melon_info = MelonModel.query.filter_by(name=name).first()
    # 组装结果数据
    temp2 = {"name": name, "type": melon_info.type, "origin": melon_info.origin, "comment": melon_info.comment}
    temp.update(temp2)
    # 将元组转化为json字符串
    result = json.dumps(temp)
    print(result)
    return result
